package com.java8.optional;

import com.entity.User;
import org.springframework.util.Assert;

import java.awt.image.ImagingOpException;
import java.util.Optional;

/**
 * <p>
 * optional
 * </p>
 *
 * @author whp
 * @since 2021/2/9
 */
public class OptionalDemo {

    public static void orelse(){
        User user = new User("john@gmail.com");
        System.out.println("Using orElse");
        //orelse 无论use 是否null，都会执行，再根据user==null 在赋值，若频繁的操作中，createNewUser连接书库，这样会造性能问题
        User result = Optional.ofNullable(user).orElse(createNewUser());
        System.out.println("Using orElseGet");
        // orElseGet 会先根据user判空，空的时候再去执行createNewUser, 有先像延迟加载
        User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
    }
    public static User createNewUser(){
        System.out.printf("new createNewUser");
       return new User("email");

    }

    public void orelseExcetion(){
        User user=null;
        Optional.ofNullable(user).orElseThrow(()->new ImagingOpException(""));
    }

    public void whenmap_thenok(){
        User user=new User("");
        Optional.ofNullable(user).map(u->{
            return u.getEmail();
        }).orElse("defult@com");
        System.out.println(user.getEmail());
    }
    public void whenMapFlat_thenok(){
        User user=new User("123@com");
        user.setImage(null);
       String defultJpg= Optional.ofNullable(user).flatMap(u->u.getImage()).orElse("dd.jpg");
        System.out.println(defultJpg);
    }

    public static void nullable(){
        Integer num1=null;
        Integer num2=5;

        // Optional 是一个容器，ofnullable 允许存入null,
        //orElse()，它的工作方式非常直接，如果有值则返回该值，否则返回传递给它的参数值
        Optional<Integer> op= Optional.of(Optional.ofNullable(num1).orElse(0));
        Assert.notNull(num1,"数字不允许为空");
        System.out.println(op.get());
    }

    public static void main(String[] args) {
        //nullable();
        orelse();
    }
}
